<?php
class mod_sys extends gModule
  {
	
    public function init(){
    	
    }
    # output areas managing
    public function outareas(){
        if (isset($_GET["add"])){
            if ($this->api->checkPOST("name", "Submit"))
              {$name = $this->api->dbo->insert("output_areas", array(
                    "value" => $this->api->escapeString($_POST["name"])
                ));
              }
            else
              {
                return $this->api->view->template("addarea");
              }
          }
        if (isset($_GET["delete"]) && is_numeric($_GET["delete"]))
          {
            $this->api->dbo->delete("output_areas", " where name='" . $this->api->escapeString($_GET["delete"]) . "'");
          }
        $Query = $this->api->dbo->select("output_areas", "*", null);
        return $this->api->view->template("outputareas", array(
            "data" => &$Query
        ));
      }
    # functions processing
    public function actions()
      {
        # checking for sorting options
        $sortsql = "modname";
        $desc = (isset($_GET["desc"])?null:"desc");
        if(isset($_GET["sort"])){
        	switch($_GET["sort"]){
        		case "funcname":$sortsql="funcname";break;
        		case "modname":$sortsql="modname";break;
        		case "guest":$sortsql="guest";break;
        		case "runwith":$sortsql="runwith";break;
        		case "onstart":$sortsql="onstart";break;
        		case "position":$sortsql="position";break;
        		case "weight":$sortsql="weight";break;
        	}
        }
	$Query = $this->api->dbo->select("functions","hash,modname,alias,funcname,guest,runmode,position,runwith,onstart,weight","order by $sortsql $desc");
	return $this->api->view->template("actions",array("data"=>&$Query,"desc"=>$desc) );
    }

    public function editaction(){
	#checking input data
    if( isset($_GET["view"]) && strlen($_GET["view"])==_HASH_LENGTH){
	$id = $this->api->escapeString($_GET["view"]);
	} else return null;
	# calling global way parser
	$this->api->cms->grabparentway("actions");
	#checking for input form data
	if( $this->api->checkPOST("guest","onstart","runwith","levels","position") && is_array($_POST["levels"])){
		list($guest,$onstart,$runwith,$position,$withmod)=$this->api->escapePOST("guest","onstart","runwith","position","withmod");
		# replacing all levellinks
		$this->api->dbo->delete("levellinks","where hash='$id'");
		foreach( $_POST["levels"] as $k=>$v){
			#adding new levellinks
			$this->api->dbo->insert("levellinks",array("hash"=>$id,"level"=>(int)$v));
		}
		# updating function information
		$this->api->dbo->update("functions","set guest='$guest',onstart='$onstart',position='$position',withmod='$withmod',runwith='$runwith' where hash='$id'");
	}
	# getting function data  
	$Query = $this->api->dbo->select("functions","*","where hash='$id' limit 1 offset 0",_RESULT_ROW);
	if( count($Query)==0) return null;
	#getting outareas list
	$Outareas = $this->api->dbo->select("output_areas","name,value","");     
	#getting all levels
	$Levels   = $this->api->dbo->select("levels","id,name");
	# modules
	$modules = $this->api->dbo->select("modules","modname",null,_RESULT_LIST);
	#getting all levellinks
	$Levellinks = $this->api->dbo->select("levellinks","level","where hash='$id'",_RESULT_LIST);
	# running with
	$Runwith = $this->api->dbo->select("functions","hash,alias","where hash not in (select hash from functions where runwith!='0' and runwith!='-1') order by alias");
	# parsing my current way
	$this->api->cms->addway("editaction","view=".$Query["hash"],$Query["alias"]);
	return $this->api->view->template("editaction.php",array("data"=>&$Query,"outareas"=>&$Outareas,"levels"=>&$Levels,"levellinks"=>&$Levellinks,"modules"=>&$modules,"runwith"=>&$Runwith),null,true);
    }

    public function levels(){
      #checking for adding new item
      if (isset($_GET["add"]))
          {
            if ($this->api->checkPOST("name", "Submit"))
              {
                $name = $this->api->escapeString($_POST["name"]);
                $this->api->dbo->insert("levels", array(
                    "name" => $name
                ));
		//$this->api->cms->sendHeader($h);
              }
            return $this->api->view->template("addlayer");
          }
	# checking for deleting
        if (isset($_GET["delete"]) && is_numeric($_GET["delete"]))
          {
            $this->api->dbo->delete("levels", "where id='" . $this->api->escapeString($_GET["delete"]) . "'");
            //$this->api->cms->sendHeader($h);
          }

        $Query = $this->api->dbo->select("levels", "name,id", "where id!='0' and id!='1' limit 100 offset 0");

        return $this->api->view->template("layers", array(
            "data" => &$Query
        ));
      }

    /*
     * Logs
     */
    public function logs(){
        $data = null;
        $this->api->log->void();
        $file = _SYS_LOG;
        if (isset($_GET["type"]))
          {
            switch ($_GET["type"])
            {
                case "auth":
                    $file = _AUTH_LOG;
                    break;
                case "sys":
                    $file = _SYS_LOG;
                    break;
                case "error":
                    $file = _ERROR_LOG;
                    break;
                default:
                    $file = _SYS_LOG;
                    break;
            }
          }
        $data = file_get_contents($this->api->parseasdir($this->api->get("logsdir")). $file);
        return $this->api->view->template("logs", array(
            "data" => nl2br($data)
        ));
      }
    
    # system parameters managing
    public function sysopt(){   	
		# checking if file is writable
    	$file=$this->api->parseconfasfile("sys-file");
    	if( !file_exists($file)  ){
    		return $this->api->message($this->lang->get("s10"));
    	}
    	if( !is_writable($file)){
    		return $this->api->message($this->lang->get("s11"));
    	}
    	# current system configuration
    	$ar = $this->parseconfasarray();
    	# checking if data entered
    	if( $this->api->checkPOST("Submit","name","viewmodel","language","urlroutermap") ){
    		$conf["name"]="\"".$this->api->escapeString($_POST["name"])."\"";
    		$conf["viewmodel"]="\"".$this->api->escapeString($_POST["viewmodel"])."\"";
    		$conf["language"]="\"".$this->api->escapeString($_POST["language"])."\"";
    		$conf["urlroutermap"]="\"".str_replace(array("\""),"",$_POST["urlroutermap"])."\"";
	    	$conf["multiaccess"]=(int)$_POST["multiaccess"];
    		$conf["logtofile"]=(int)$_POST["logtofile"];
    		$conf["dbopersistent"]=isset($_POST["dbopersistent"])?1:0;    		
			# testing dbo connection
			$db = $_POST["db"];
			$dbconf = "array(";
			$dbprobe = true;
			$i=0;
			foreach( $db as $k=>&$v ){
				$v["password"]=base64_encode($v["password"]);
				$probe = $this->api->dbo->probeconnection($v["driver"],$v);				
				if( !$probe){
					print $this->api->message("Cannot connect to the database '".$v["driver"]."'");
					$this->api->htmlvardump($this->api->errors->last());
					$dbprobe = false;
					break;
				}
				$dbconf .=($i>0?",\n\t":null)."\"".$v["driver"]."\"=>array(\"server\"=>\"".$v["server"]."\",\"db\"=>\"".$v["db"]."\",\"port\"=>\"".$v["port"]."\",\"user\"=>\"".$v["user"]."\",\"password\"=>\"".$v["password"]."\")";			
				$i++;
			}
			$dbconf .= ")";
			# checking if database connected successfully
			if($dbprobe) {
				$conf["dboconf"]=$dbconf;
				if( count($db)>1) {
					$conf["dbodatareplication"]=isset($_POST["dbodatareplication"])?1:0;	
				} else {
					if( array_key_exists("dbodatareplication",$ar)){
						unset($ar["dbodatareplication"]);
					}
				}
			}
			# writing system configuration
    		foreach($conf as $k=>$v){
    			$ar[$k]=$v;
    		}
    		$this->writesysconf($ar);
    		$this->api->redirect("sysopt");
    	}
    	# current system configuration
    	$ar = $this->parseconfasarray();
    	$sys["language"]= array_key_exists("language",$ar)?$ar["language"]:null;
    	$sys["name"]= array_key_exists("language",$ar)?$ar["name"]:null;
    	$sys["viewmodel"]= array_key_exists("viewmodel",$ar)?$ar["viewmodel"]:"default";
    	$sys["urlroutermap"]= array_key_exists("urlroutermap",$ar)?$ar["urlroutermap"]:$this->api->urlrouter->getdefaultmap();
    	$sys["multiaccess"]= array_key_exists("multiaccess",$ar)?$ar["multiaccess"]:$this->api->get("multiaccess");
    	$sys["logtofile"]= array_key_exists("logtofile",$ar)?$ar["logtofile"]:$this->api->get("logtofile");
		$sys["dbopersistent"]=array_key_exists("dbopersistent",$ar)?$ar["dbopersistent"]:$this->api->get("dbopersistent");
    	# checking for datareplication
    	if( count($this->api->dbo->getconnected())>1){
    		$sys["dbodatareplication"]=array_key_exists("dbodatareplication",$ar)?$ar["dbodatareplication"]:0;
    	} else 
    		$sys["dbodatareplication"]=0;
		
		
    	$dboold = $this->api->get("dboconf");
    	$dbo = array();
    	foreach( $dboold as $k=>$v){
    		$v["driver"]=$k;
    		$v["password"]=base64_decode($v["password"]);
    		$dbo[]=$v;
    	}
    	    	
    	foreach( $sys as $k=>&$v){
    		$v = preg_replace("/^(\"|')(.+)(\"|')$/","$2",$v);
    	}
    	# building output template
    	return $this->api->view->template("options.php",array("langs"=>$this->api->GetSysLanguages(),"sys"=>$sys,"dbo"=>$dbo,
    		"drivers"=>$this->api->dbo->getsupported()),null,true);
    }
    
    private function parseconfasarray(){
		$file = $this->api->parseconfasfile("sysappconf");
		$data = file_get_contents($file);
		preg_match_all("/\\\$Gepard\-\>set\s*\(\s*(\"|')?([^,\"']+)(\"|')?\s*\,\s*(((?!\)\s*;).)*?)\s*\)\s*\;/is",$data,$tmp);
		$ar = array_combine(array_values($tmp[2]),array_values($tmp[4]));
		return $ar;
    }    
    
    private function writesysconf(array $array){
    	$file = $this->api->parseconfasfile("sysappconf");
    	$data = "<?php\n#Gepard application configuration file\n";
    	$data .="#Generated by web interface, ".date("Y-m-d H:i:s").", from ip: ".$this->api->user->GetUserIP()."\n";
    	foreach( $array as $k=>&$v){
    		$data .="\$Gepard->set(\"".$k."\",".$v.");\n";
    	}
    	$data .="\n?>";
    	file_put_contents($file,$data);
    }

    public function install()
      {
      }

    public function uninstall()
      {
      }

  }